"use client";
import { useState, useEffect } from "react";

interface Geo {
  lat: string;
  lng: string;
}

interface Address {
  street: string;
  suite: string;
  city: string;
  zipcode: string;
  geo: Geo;
}

interface Company {
  name: string;
  catchPhrase: string;
  bs: string;
}
//  定义了一个 User 类， 然后注意 address 也是一个对象，同理 company 也是一个对象
interface User {
  id: number;
  name: string;
  username: string;
  email: string;
  address: Address;
  phone: string;
  website: string;
  company: Company;
}
export default function UserProfileLoader() {
  // 定义状态  user 用户 ； isLoading 是否正在加载中
  const [user, setUser] = useState<User | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  // 模拟后端数据获取 (类似于 Controller 调用 Service)
  useEffect(() => {
    //定义一个一步函数
    async function fetchData() {
      try {
        console.log("开始获取用户信息...");
        // 模拟延迟2秒
        await new Promise((resolve) => setTimeout(resolve, 2000));

        const response = await fetch(
          "https://jsonplaceholder.typicode.com/users/1"
        );
        const data: User = await response.json();
        console.log("用户信息获取成功：", data);

        // 更新状态
        setUser(data);
        setIsLoading(false); //关闭加载转圈
      } catch (error) {
        console.log("获取用户信息失败：", error);
        setIsLoading(false);
      }
    }

    // 调用函数
    fetchData();
  }, []); // 空数组表示：只在页面第一次加载时运行

  if (isLoading) {
    return <div style={{ padding: "50px" }}>Loading...</div>;
  }

  if (!user) {
    return <div style={{ padding: "50px" }}>Loading...</div>;
  }

  return (
    <div style={{ padding: "50px", fontFamily: "sans-serif" }}>
      <h1>用户 档案（API 数据）</h1>
      <div
        style={{
          padding: "20px",
          border: "1px solid #ccc",
          borderRadius: "10px",
          boxShadow: "0 2px 4px rgba(0, 0, 0, 0.1)",
        }}
      >
        <p>
          <strong>ID:</strong> {user.id}
        </p>
        <p>
          <strong>姓名:</strong> {user.name}
        </p>
        <p>
          <strong>用户名:</strong> {user.username}
        </p>
        <p>
          <strong>邮箱:</strong> {user.email}
        </p>
        <p>
          <strong>电话:</strong> {user.phone}
        </p>
        <p>
          <strong>网站:</strong> {user.website}
        </p>
        <p>
          <strong>地址:</strong> {user.address.street}, {user.address.suite},{" "}
          {user.address.city}, {user.address.zipcode}
        </p>
        <p>
          <strong>地理位置:</strong> 纬度 {user.address.geo.lat}, 经度{" "}
          {user.address.geo.lng}
        </p>
        <p>
          <strong>公司:</strong> {user.company.name} -{" "}
          {user.company.catchPhrase}
        </p>
      </div>
      <button
        onClick={() => window.location.reload()}
        style={{ marginTop: "20px", padding: "10px" }}
      >
        刷新页面重试
      </button>
    </div>
  );
}
